package com.sze.volanmenetrendgyor;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

public class LinesConnector {
	static String url = "http://ihm.trumind.hu/api?task=getAllLines";

	public static ArrayList<LinesClass> getLinesFromNet() throws IOException,
			JsonIOException, JsonSyntaxException {

		InputStream source = retrieveStream(url);

		Gson gson = new Gson();

		Reader reader = new InputStreamReader(source);

		Type listType = new TypeToken<ArrayList<LinesClass>>() {
		}.getType();
		ArrayList<LinesClass> linesList = gson.fromJson(reader, listType);
		return linesList;
	}

	private static InputStream retrieveStream(String url) throws IOException {

		DefaultHttpClient client = new DefaultHttpClient();

		HttpGet getRequest = new HttpGet(url);

		try {

			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
				throw new IOException("HttpError: " + statusCode + " for URL "
						+ url);
			}

			HttpEntity getResponseEntity = getResponse.getEntity();
			return getResponseEntity.getContent();

		} catch (IOException e) {
			getRequest.abort();
			Log.d("IOException: " + url, e.getMessage());
			throw e;
		}
	}
}
